import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';
import {getKnowledgeList} from '../services/index'
import {IknowledgeListItem} from '../utils/interface'

export interface KnowledgeModelState {
  knowledgeList:Array<IknowledgeListItem>
}

export interface IndexModelType {
  namespace: 'knowledge';
  state: KnowledgeModelState;
  effects: {
    getKnowledgeList: Effect;
  };
  reducers: {
    save: Reducer<KnowledgeModelState>;
    // 启用 immer 之后
    // save: ImmerReducer<IndexModelState>;
  };
  subscriptions: { setup: Subscription };
}

const Knowledge: IndexModelType = {
  namespace: 'knowledge',

  state: {
    knowledgeList:[]
  },

  effects: {
    *getKnowledgeList({ payload }, { call, put }) {
      let res = yield call(getKnowledgeList,payload)
      yield put({
        type:'save',
        payload:{
          knowledgeList:res.data[0]
        }
      })
    },
  },
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    // 启用 immer 之后
    // save(state, action) {
    //   state.name = action.payload;
    // },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname === '/') {
          dispatch({
            type: 'query',
          });
        }
      });
    },
  },
};

export default Knowledge;